package com.sensePlusVR.activity.user;

import android.os.Bundle;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.LinkMovementMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TextView.BufferType;
import android.widget.Toast;

import com.sensePlusVR.activity.listener.AEditTextCallBack;
import com.sensePlusVR.activity.mine.HyperlinkSettingActivity;
import com.sensePlusVR.base.BaseActivity;
import com.sensePlusVR.main.R;
import com.sensePlusVR.net.NetRequestManager;
import com.sensePlusVR.utils.AppManager;
import com.sensePlusVR.utils.Constant;
import com.sensePlusVR.utils.EditTextUtils;
import com.sensePlusVR.utils.MyLog;
import com.sensePlusVR.utils.MyPageJump;
import com.sensePlusVR.utils.MySharedPreferences;
import com.sensePlusVR.utils.MyToast;
import com.sensePlusVR.utils.StringUtils;
import com.sensePlusVR.widget.EditTextDeleteAll;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

/**
 * 
 * @author: Loren
 * @create: 2016-7-4下午7:38:18
 * @desc: 注册界面
 *
 */
@ContentView(R.layout.activity_register)
public class RegisterActivity extends BaseActivity implements OnCheckedChangeListener{

	private static final String TAG = RegisterActivity.class.getSimpleName();
	
	@ViewInject(R.id.title_bar_title_tv)
	private TextView tvTitle;

	@ViewInject(R.id.register_username)
	private EditTextDeleteAll edtUserName;// 邮箱
	
	@ViewInject(R.id.register_eidit_prompt_linear)
	private LinearLayout register_eidit_prompt_linear;
	
	@ViewInject(R.id.register_password)
	private EditTextDeleteAll edtTxtPassword;// 密码

	@ViewInject(R.id.register_show_pwd_iv)
	private ImageView tvShowOrHide;
	
	@ViewInject(R.id.register_term)
	private CheckBox register_term;// 条款选择框
	
	@ViewInject(R.id.register_term_tv)
	private TextView register_term_tv;
	
	@ViewInject(R.id.register_name_delete_iv)
	private ImageView register_name_delete_iv;
	
	@ViewInject(R.id.register_pwd_delete_iv)
	private ImageView register_pwd_delete_iv;

	static String loginName;
	static String password;
	static String email;
	
	private boolean showPassword = false;//显示隐藏pwd标记
	private boolean isChecked = false;//是否选中标记
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
	}
	
	
	@Override
	public void setMyContentView() {
		x.view().inject(this);
	}
	
	@Override
	public void initView() {
		super.initView();
		AppManager.getInstance().addActivity(this);
		
		isChecked = register_term.isChecked();
		
		boolean isShowCPUInfo = MySharedPreferences.getBoolean2(this,
				MySharedPreferences.NAME_NOT_CLEAR,Constant.IS_FIRST_SHOW_CPUINFO);
		if(!isShowCPUInfo){
			getMobileparamsToTip();
		}
		
		
        tvTitle.setText(R.string.login_signup);
        register_term.setOnCheckedChangeListener(this);
		
        
        avoidHintColor(register_term_tv);
        
        
        edtUserName.setOnAEditTextCallBack(editTextCallBack);
        edtTxtPassword.setOnAEditTextCallBack(editTextCallBack);
        
		StringBuilder sb = new StringBuilder();
		String likeTerms = sb.append(getResources().getString(R.string.register_terms)).append(" " + getResources().getString(R.string.and) + " ").append(getResources().getString(R.string.register_conditions)).toString();
		MyLog.d(TAG, "likeTerms : " + likeTerms);
		register_term_tv.setMovementMethod(LinkMovementMethod.getInstance());
		register_term_tv.setText(addClickablePart(likeTerms), BufferType.SPANNABLE);
	}
	
	
	public void getMobileparamsToTip() {
		/*
		MobileParamsDetect mobileParamsDetectObj = new MobileParamsDetect();
		String mobileParamsDetect = mobileParamsDetectObj.getPlayLevelHints(this);
		
		if (!mobileParamsDetect.equals(MobileParamsDetect.TIP_ERROR)) {
			MySharedPreferences.save2(this, MySharedPreferences.NAME_NOT_CLEAR,
					Constant.IS_FIRST_SHOW_CPUINFO, true);

			if (!mobileParamsDetect.equals(MobileParamsDetect.TIP_NONE)
					&& mobileParamsDetect.trim() != "") {
				DialogUtils.showConfirmDialogConfirm(RegisterActivity.this,
						null, mobileParamsDetect,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
//								if (MobileParamsDetect.isBelowJellyBeanMr2()) {
//									AppManager.getInstance().exitApp(
//											getApplicationContext());
//								}
							}
						});
			}
		}else{
			mobileParamsDetectObj.setCPUInfoCallback(cpuInfoListener);
		}

		MyLog.d(TAG, "mobileParamsDetect :　" + mobileParamsDetect);
		*/
	}
	
	/*
	private CPUInfoListener cpuInfoListener = new CPUInfoListener() {
		
		@Override
		public void onCPUInfoListener(CpuInfo cpuInfo) {
			MyLog.d(TAG, "cpuInfoListenerFirst cpuInfo : " + cpuInfo);
			
			getMobileparamsToTip();
			
		}
	};
	*/
	
	
	private AEditTextCallBack editTextCallBack = new AEditTextCallBack() {
		
		@Override
		public void onDeleteVisible(View view, boolean isVisible) {
			
			switch (view.getId()) {
			case R.id.register_username:
				
				if(isVisible){
				
					register_name_delete_iv.setVisibility(View.VISIBLE);
					
				}else{
					
					register_name_delete_iv.setVisibility(View.INVISIBLE);
					
				}
				
				break;
			case R.id.register_password:
				
				if(isVisible){
					
					register_pwd_delete_iv.setVisibility(View.VISIBLE);
					
				}else{
					
					register_pwd_delete_iv.setVisibility(View.INVISIBLE);
				}
				
				break;
			}
		}
		
		public void onBottomTipVisible(View view, boolean isVisible) {
			switch (view.getId()) {
			case R.id.register_password:
				if(isVisible){
					register_eidit_prompt_linear.setVisibility(View.VISIBLE);
				}else{
					register_eidit_prompt_linear.setVisibility(View.INVISIBLE);
				}
				break;

			}
		};
	};
	
	/**
	 * 字符添加点击链接
	 * @param str
	 * @return
	 */
	private SpannableStringBuilder addClickablePart(String str) {
		SpannableString spanStr = new SpannableString(getResources().getString(R.string.register_regular1) + " ");
		SpannableStringBuilder ssb = new SpannableStringBuilder(spanStr);
		ssb.append(str);
		String[] likeUsers = str.split(getResources().getString(R.string.and));
		if (likeUsers.length > 0) {
			// 最后一个
			for (int i = 0; i < likeUsers.length; i++) {
				final String name = likeUsers[i];
				final int start = str.indexOf(name) + spanStr.length();
				ssb.setSpan(new ClickableSpan() {

					@Override
					public void onClick(View widget) {
						MyLog.d(TAG, "name : " + name);
						if(name.trim().contains(getResources().getString(R.string.register_terms))){
							MyPageJump.pageJumpAddString(RegisterActivity.this, HyperlinkSettingActivity.class, 
									Constant.INTENT_HYPERLINK_KEY, Constant.INTENT_HYPERLINK_OURTERMS);
						}else if(name.trim().contains(getResources().getString(R.string.register_conditions))){
							MyPageJump.pageJumpAddString(RegisterActivity.this, HyperlinkSettingActivity.class, 
									Constant.INTENT_HYPERLINK_KEY, Constant.INTENT_HYPERLINK_CONDITIONS);
						}
						
					}

					@Override
					public void updateDrawState(TextPaint ds) {
						super.updateDrawState(ds);
						ds.setColor(getResources().getColor(R.color.app_text_color_gray1)); // 设置文本颜色
						// 去掉下划线
						ds.setUnderlineText(false);
					}

				}, start, start + name.length(), 0);
			}
		}
		return ssb;
	
	}
	
	   private void avoidHintColor(View view){
           if(view instanceof TextView)
               ((TextView)view).setHighlightColor(getResources().getColor(android.R.color.transparent));
       }
	
	@Event(value = {R.id.title_bar_left_ib,
            R.id.register_register,R.id.register_show_pwd_iv,R.id.register_name_delete_iv,R.id.register_pwd_delete_iv})
	private void setViewOnClick(View view){
		switch (view.getId()) {
		case R.id.title_bar_left_ib: {
			onBackPressed();
			break;
		}

		case R.id.register_register: {
			mySubmit();
			break;
		}

		case R.id.register_show_pwd_iv:
			MyLog.d(TAG, "register_show_pwd_iv");
			if (showPassword) {
				if (checkInputData(edtTxtPassword)) {
					showPassword = !showPassword;
					tvShowOrHide.setImageResource(R.drawable.show_icon);
					edtTxtPassword
							.setTransformationMethod(PasswordTransformationMethod
									.getInstance());
					edtTxtPassword.setSelection(edtTxtPassword.getText()
							.toString().length());
				}

			} else {
				if (checkInputData(edtTxtPassword)) {
					showPassword = !showPassword;
					tvShowOrHide.setImageResource(R.drawable.hide_icon);
					edtTxtPassword
							.setTransformationMethod(HideReturnsTransformationMethod
									.getInstance());
					edtTxtPassword.setSelection(edtTxtPassword.getText()
							.toString().length());
				}

			}
			break;
		case R.id.register_name_delete_iv:
			edtUserName.setText("");
			break;
		case R.id.register_pwd_delete_iv:
			edtTxtPassword.setText("");
			break;
		}
	}
	
	private boolean checkInputData(EditText editText){
		  if (StringUtils.isEmpty(EditTextUtils.getText(editText))) {
	            return false;
	        }
		return true;
	}
	
	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		 this.isChecked = isChecked;
		 MyLog.d(TAG, "isChecked : " + isChecked);
	}
	
    /**
     * 注册并登陆处理
     * 
     */
    private void mySubmit() {
        if (checkImputData()) {
            setInputData();
            NetRequestManager.startRegisterRequestResult(RegisterActivity.this,loginName.trim(),password);
        }
    }
    

    /**
     * 注册处理-画面项目check
     * 
     * @return check结果（true:通过/ false:未通过）
     */
    private boolean checkImputData() {

        loginName = EditTextUtils.getText(edtUserName).trim();

        // 邮箱的格式验证
        if (StringUtils.isEmpty(loginName)) {
        	MyToast.showMessage(getApplicationContext(),
                    R.string.msg_common_e_null_email);
            return false;
        }
        
        if (!StringUtils.isEmail(loginName)) {
        	MyToast.showMessage(getApplicationContext(),
                    R.string.msg_common_e_phone_number_email);
            return false;
        }
        // 密码
        if (StringUtils.isEmpty(EditTextUtils.getText(edtTxtPassword))) {
        	MyToast.showMessage(getApplicationContext(),
                    R.string.msg_common_e_null_password_confirm);
            return false;
        } else {
            // 密码长度判断
            if (EditTextUtils.getText(edtTxtPassword).length() < Constant.NUMBER_6
                    || EditTextUtils.getText(edtTxtPassword).length() > Constant.NUMBER_15 || !StringUtils.isNumAndCode(EditTextUtils.getText(edtTxtPassword))) {
                Toast.makeText(getApplicationContext(),
                        R.string.pwd_min_length, Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        
    	if(!isChecked){
    		MyToast.showMessage(this, R.string.register_regular);
    		return false;
    	}
    	
        return true;
    }
    
    /**
     * check通过后,赋值
     * 
     */
    private void setInputData() {
    	
        password = EditTextUtils.getText(edtTxtPassword);
        
        email = EditTextUtils.getText(edtUserName);

    }
    
	@Override
	public void onBackPressed() {
		super.onBackPressed();
        AppManager.getInstance().finishActivity(this);
	}
}
